<template>
  <a-tree checkable :tree-data="columns" @check="handleCheck" key="title" />
  <a-table
    :columns="tableColumns"
    :data-source="data"
    bordered
    size="middle"
    :scroll="{ x: 'calc(700px + 50%)', y: 240 }"
  />
</template>
<script setup>
import { ref } from "vue";
import { columns } from "../mock/tree";
const tableColumns = ref([]);
// 1. addKeys方法函数：为每个columns添加一个 ['0-1', '0-2', '0-6-1', '0-6-2', '0-6-0', '0-6']规律的key
function addKeys(data, parentKey = "0", index = 0) {
  data.forEach((item, i) => {
    const key = parentKey ? `${parentKey}-${i}` : `${i}`;
    item.key = key;
    if (item.children && item.children.length > 0) {
      addKeys(item.children, key, i);
    }
  });
}
addKeys(columns);
// 2. 递归函数extractCheckedNodes，对传入的tree数据及checkedKeys匹配得到被勾选的数据包
function extractCheckedNodes(treeData, checkedKeys) {
  const result = [];
  for (const node of treeData) {
    if (checkedKeys.includes(node.key)) {
      const newNode = { ...node };
      delete newNode.children;
      result.push(newNode);
      if (node.children && node.children.length > 0) {
        newNode.children = extractCheckedNodes(node.children, checkedKeys);
      }
    } else if (node.children && node.children.length > 0) {
      const newChildren = extractCheckedNodes(node.children, checkedKeys);
      if (newChildren.length > 0) {
        const newNode = { ...node };
        newNode.children = newChildren;
        result.push(newNode);
      }
    }
  }
  return result;
}
const handleCheck = (checkedKeys, ev) => {
  console.log(checkedKeys);
  let arr = extractCheckedNodes(columns, checkedKeys);
  console.log(arr);
  tableColumns.value = arr; //将递归得到的columns动态配置给表格
};
//此处的data数据包需要带有跟columns一致的所有字段
const data = [...Array(100)].map((_, i) => ({
  key: i,
  name: "John Brown",
  age: i + 1,
  street: "Lake Park",
  building: "C",
  number: 2035,
  companyAddress: "Lake Street 42",
  companyName: "SoftLake Co",
  gender: "M",
}));
</script>
